// 云函数入口文件
const cloud = require('wx-server-sdk');

cloud.init();

/**
 * @breief 获取用户所有的帖子，不分类别，按照时间排序
 * event参数说明
 * @param {Number} skip 跳过的记录数
 * @param {Number} limit 获取记录的数量限制
 * 返回值
 * @return {Object}
 *  errCode 错误码，0-返回，1-未注册，2-请求失败
 *  list 帖子列表，内部元素格式如下：
 * {
    "_id": "68426679629a2c8604b15d5b6b283e4f",
    "nickName": "lyc",
    "_openid": "o9Ifc5BXNXoDvCX1dub-LLSK928I",
    "avatarUrl": "https://thirdwx.qlogo.cn/mmopen/vi_32/N9IHq7Qkjq6oorguhJG8YcMgZGibu4Sz8ujS1Ns6SaNYMicySHw4icOvvic58xAXrxNE2leNsiahS6lMcRU4iamwfXlw/132",
    "budget": "66",
    "members": ["o9Ifc5BXNXoDvCX1dub-LLSK928I"],
    "name": "66",
    "title": "666",
    "date": "2022-6-3",
    "imgUrl": "cloud://cloud1-3ghpsj56f64f6900.636c-cloud1-3ghpsj56f64f6900-1310116404/team_img/test.png",
    "content": "666"
   }
 */
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext();
  const openid = wxContext.OPENID;
  const db = cloud.database();
  const _ = db.command;
  const $ = _.aggregate;
  const LIMIT = 100;
  // 查询是否注册
  var userInfo = await db.collection('user').where({
    _openid: openid
  }).get();
  if (userInfo.data.length == 0) {
    return {
      errCode: 1
    };
  }
  // 计数
  const count = await db.collection('post').where({
    _openid: openid
  }).count();
  console.log('count', count);
  // 查询过程
  var tasks = [];
  for (var i = 0; i < count.total / LIMIT; i++) {
    var t = db.collection('post')
      .aggregate()
      .match({
        _openid: openid
      })
      .skip(i * LIMIT)
      .limit(LIMIT)
      .lookup({
        from: 'user',
        localField: '_openid',
        foreignField: '_openid',
        as: 'user'
      })
      .replaceRoot({
        newRoot: $.mergeObjects([$.arrayElemAt(['$user', 0]), '$$ROOT'])
      })
      .project({
        _openid: 1,
        nickName: 1,
        avatarUrl: 1,
        budget: 1,
        members: 1,
        name: 1,
        title: 1,
        date: 1,
        imgUrl: 1,
        content: 1,
        type: 1
      })
      .end();
    tasks.push(t);
  }
  // reduce所有请求
  try {
    var postList = (await Promise.all(tasks)).reduce((acc, cur) => {
      return {
        list: acc.list.concat(cur.list)
      };
    });
    postList = postList.list;
    console.log('query res', postList);
    // 排序
    postList.sort((a, b) => {
      var gt = -1, eq = 0, lt = 1;
      if (a.date > b.date) return gt;
      else if (a.date < b.date) return lt;
      else return eq;
    })
    // 返回数据和错误码0
    return {
      data: postList,
      errCode: 0
    };
  } catch (err) {
    // 返回错误码2
    return {
      errCode: 2
    };
  }
}